package com.dingwen.treasure.file.controller;

import com.alibaba.excel.EasyExcel;
import com.dingwen.treasure.base.controller.BaseViewController;
import com.dingwen.treasure.base.exception.BusinessException;
import com.dingwen.treasure.base.pojo.vo.Result;
import com.dingwen.treasure.easyexcel.ExcelEntity;
import com.dingwen.treasure.file.component.FileComponent;
import com.dingwen.treasure.file.constant.FileConstant;
import com.dingwen.treasure.file.listener.ExcelEntityAnalysisEventListener;
import com.dingwen.treasure.file.service.ExcelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 　EasyExcelController
 * 　@author dingwen
 * 　@date 2022/8/2
 */
@Api(tags = "easy excel API")
@RestController
@Slf4j
@RequestMapping("excel")
public class EasyExcelController implements BaseViewController {

    /**
     * excelService
     */
    @Resource
    private ExcelService excelService;


    @Resource
    private FileComponent fileComponent;

    @ApiOperation(value = "excel导入", response = Result.class)
    @GetMapping("import")
    public Result<List<ExcelEntity>> importByExcel() {
        EasyExcel.read(
                        "treasure_file.xlsx",
                        ExcelEntity.class,
                        new ExcelEntityAnalysisEventListener()
                )
                .sheet()
                .doRead();
        return success();
    }

    @ApiOperation(value = "通过excel导出")
    @GetMapping("export")
    public void exportByExcel(HttpServletResponse response) {
        ExcelEntity entity = ExcelEntity.builder()
                .fileId("666")
                .entity(ExcelEntity.builder().fileId("999").build())
                .excelEntities(Collections.singletonList(ExcelEntity.builder().fileId("888").build()))
                .build();
        excelService.download(response, entity);
    }


    @ApiOperation(value = "通过实体注解导出")
    @GetMapping
    public void importSuspectedRecords(HttpServletResponse response) {
        try {
            List<ExcelEntity> entities = new ArrayList<>();
            fileComponent.readyDownload(response, LocalDateTime.now().toString(), FileConstant.EXCEL_FILE_SUFFIX);
            EasyExcel.write(response.getOutputStream(), ExcelEntity.class).sheet().doWrite(entities);
        } catch (IOException e) {
            String msg = "通过实体注解导出发生错误";
            log.error(msg, e.getMessage());
            throw new BusinessException(msg);
        }
    }
}
